package main

import (
	"fmt"
	// _ "net/http/pprof"
	"os"
	"os/signal"
	"syscall"
	"time"
 
	"github.com/buaazp/fasthttprouter"
	"github.com/valyala/fasthttp"
	"gitlab.gaodun.com/golib/graceful"
	"permission/api"
	"permission/vigo_loger"
)

var NetworkAddr = "0.0.0.0:6061"

const maxWaitTime = 2 * time.Second

func getServer(router *fasthttprouter.Router) *fasthttp.Server {
	return &fasthttp.Server{
		// see https://godoc.org/github.com/valyala/fasthttp#Server
		Handler: router.Handler,
		Name:    "permission-api",
		// The maximum number of concurrent connections the server may serve.
		Concurrency:          100000,
		DisableKeepalive:     true,
		ReadBufferSize:       1024 * 16,
		WriteBufferSize:      1024 * 16,
		ReadTimeout:          60 * time.Second,
		WriteTimeout:         60 * time.Second,
		MaxConnsPerIP:        100000,
		MaxRequestsPerConn:   100000,
		MaxKeepaliveDuration: 120 * time.Second,
		MaxRequestBodySize:   512 * 1024 * 1024,
	}
}

func main() {

	exit := make(chan os.Signal, 1)
	signal.Notify(exit, os.Interrupt,
		syscall.SIGTERM, syscall.SIGINT,
		syscall.SIGHUP,
		//syscall.SIGUSR1,
		//syscall.SIGUSR2,
	)

	router := api.GetRouter()
	ucenterServer := getServer(router)

	nowTime := time.Unix(time.Now().Unix(), 0).Format("2006-01-02 15:04:05")
	fmt.Println(nowTime + " start permission-api Server 0.0.0.0:6061!")
	vigo_loger.AddGrayLog(nowTime + " start permission-api Server 0.0.0.0:6061!")

	networkAddr := graceful.NewGracefulListener(NetworkAddr, maxWaitTime)
	// 预热数据
	//go user_info.PreheatAPI()
	go func() {
		if err := ucenterServer.Serve(networkAddr); err != nil {
			vigo_loger.AddGrayLog("start fasthttp fail:" + err.Error())
			fmt.Println("start fasthttp fail:", err.Error())
		}
	}()

	// go func() {
	// 	http.ListenAndServe("0.0.0.0:8061", nil) // 启动默认的 http 服务，可以使用自带的路由
	// }()
	s := <-exit
	fmt.Println("shutting down server .", s)
	err := networkAddr.Close()
	fmt.Println("Server gracefully stopped:", err)

	return
}
